def owner_required(Model):
    '''
This decorator allows edit for the owner of the record. Snippet applies for every model that has ForeignKey to User. Works in User model too. Works with other decorators as permission_required or similar.

Usage

@permission_required('blogs.change_entry')
@owner_required(Entry)
def manage_entry(request, object_id=None, object=None, can_edit=False):
...

Decorator populates object and can_edit kwargs if object_id present, otherwise just returns original view function. 
'''
    def _decorator(func):
        def _closure(request, *args, **kwargs):
            user = request.user
            if kwargs:
                object_id = int(kwargs.values()[0])
                kwargs['object'] = get_object_or_404(Model, pk=object_id)
                if user.is_superuser:
                    kwargs['can_edit'] = True
                else:
                    if user.__class__ == Model:
                        kwargs['can_edit'] = object_id == user.id
                    else:
                        sets = [rel.get_accessor_name() for rel in user._meta.get_all_related_objects() if rel.model == Model]
                        if sets:
                            kwargs['can_edit'] = object_id in [o.id for o in eval('user.%s.all()' % sets[0])]
            return func(request, *args, **kwargs)
        _closure.__name__ = func.__name__
        _closure.__doc___ = func.__doc__
        _closure.__module___ = func.__module__
        return _closure
    return _decorator
